﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Principal;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Threading;

namespace CoreTest;

public partial class App : System.Windows.Application
{
    const string MYCOSLOGSOURCE = "MyWEM Application";
    const string MYCOSLOGNAME = "MyWEM";

    static EventLog Log = new EventLog(MYCOSLOGNAME);
    static readonly string machine = Environment.MachineName;
    public static readonly DAServer Server = new DAServer();

    static IPrincipal _princ;
    public static IPrincipal Principal
    {
        get => _princ;
        set => _princ = value;
    }

    public static string LogSource =>
        machine + "\\" + (_princ == null ? null : _princ.Identity.Name);

    static Queue<string> eventLog = new Queue<string>(300);
    public static IEnumerable<string> Events => eventLog;

    static App()
    {
        var curr = Process.GetCurrentProcess();
        foreach (var process in Process.GetProcessesByName(curr.ProcessName))
        {
            if (process.Id != curr.Id)
            {
                System.Windows.MessageBox.Show("程序已启动!");
                Environment.Exit(0);
            }
        }
        if (!EventLog.SourceExists(MYCOSLOGSOURCE))
            EventLog.CreateEventSource(MYCOSLOGSOURCE, MYCOSLOGNAME);
    }

    public static void AddErrorLog(Exception e)
    {
        string err = "";
        Exception exp = e;
        while (exp != null)
        {
            err += string.Format("\n {0}", exp.Message);
            exp = exp.InnerException;
        }
        err += string.Format("\n {0}", e.StackTrace);
        Log.Source = MYCOSLOGSOURCE;
        Log.WriteEntry(err, EventLogEntryType.Error);
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        Current.DispatcherUnhandledException += App_DispatcherUnhandledException;
        base.OnStartup(e);

        var w1 = new TagMonitor();
        w1.WindowStartupLocation = WindowStartupLocation.Manual;
        var r1 = Screen.AllScreens[0].WorkingArea;
        w1.Top = r1.Top;
        w1.Left = r1.Left;
        w1.Show();
    }

    protected override void OnExit(ExitEventArgs e)
    {
        base.OnExit(e);
        Server.Dispose();
        ConfigCache.SaveConfig();
    }

    void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
    {
        AddErrorLog(e.Exception);
        e.Handled = true;
    }
}
